package com.example.myspringai;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class HistoryMessageAOP {

    public final static Map<String, List<Message>> historyMessages = new ConcurrentHashMap<>();

    @Pointcut("execution(* com.example.myspringai.controller.AIChatController.chatRoom(..))")
    public void loggingPointcut() {
        System.out.println("切面定义");
    }

    @AfterReturning(value = "loggingPointcut()", returning = "result")
    public void testAfter(JoinPoint joinPoint, Object result) {
        Flux<String> flux = (Flux<String>) result;
        Object[] args = joinPoint.getArgs();
        Object message = args[0];
        String roomId = (String) args[1];
        //模拟查询房间会话记录
        List<Message> messages = historyMessages.get(roomId);
        //获取 AI 回复信息
        Mono<String> reducedValue = flux.reduce(String::concat);
        String aiMessage = reducedValue.block();
        //将 AI 回复信息存入房间会话
        messages.add(new AssistantMessage(aiMessage));
        //模拟将房间会话信息存入数据库
        historyMessages.put(roomId, messages);
    }
}
